/**
 * 扩充underscore工具方法
 * 
 * @author Gill Gong
 * @date 2019-01-29
 */

import _ from 'underscore'

_.mixin({
  type: function (obj) {
    var toString = Object.prototype.toString;
    var map = {
      '[object Boolean]': 'boolean',
      '[object Number]': 'number',
      '[object String]': 'string',
      '[object Function]': 'function',
      '[object Array]': 'array',
      '[object Date]': 'date',
      '[object RegExp]': 'regExp',
      '[object Undefined]': 'undefined',
      '[object Null]': 'null',
      '[object Object]': 'object'
    };

    return map[toString.call(obj)];
  },

  cloneDeep: function cloneDeep(data) {
    var t = _.type(data), o, i, ni;

    if (t === 'array') {
      o = [];
    } else if (t === 'object') {
      o = {};
    } else {
      return data;
    }

    if (t === 'array') {
      for (i = 0, ni = data.length; i < ni; i++) {
        o.push(_.cloneDeep(data[i]));
      }
      return o;
    } else if (t === 'object') {
      for (i in data) {
        o[i] = _.cloneDeep(data[i]);
      }
      return o;
    }
  },

  eachRight: function (array, handler, cxt) {
    var length;

    if (_.isArray(array) && _.isFunction(handler)) {

      for (length = array.length - 1; length > -1; length--) {
        handler.call(cxt || {}, array[length], length, array)
      }
    }
  },

  startsWith: function (content, target) {
    var reg = new RegExp("^" + target);

    return reg.test(content);
  },

  endsWith: function (content, target) {
    var reg = new RegExp(target + "$");

    return reg.test(content);
  },

  trim: function (content) {

    return content.replace(/^\s+/, '').replace(/\s+$/, '');
  }
})

global._ = _

export default _